package com.avic.system.controller;

import com.avic.system.common.constant.CacheConstant;
import com.avic.system.common.constant.LocalCacheConstant;
import com.avic.system.common.constant.SystemLogConstant;
import com.avic.system.common.constant.UserConstant;
import com.avic.system.common.convertor.SystemMenuConvertor;
import com.avic.system.common.convertor.SystemUserConvertor;
import com.avic.system.common.enums.UserStateEnums;
import com.avic.system.common.enums.UserTypeEnums;
import com.avic.system.common.util.AssertUtil;
import com.avic.system.common.util.ex.BizErrorCode;
import com.avic.system.common.util.lang.BaseResponse;
import com.avic.system.common.util.lang.ServiceCallBack;
import com.avic.system.controller.info.SystemUserListInfo;
import com.avic.system.controller.info.UserMenuInfo;
import com.avic.system.controller.info.UserRightInfo;
import com.avic.system.controller.request.ChangePasswordReq;
import com.avic.system.controller.request.CreateSystemUserReq;
import com.avic.system.controller.request.GetLoginLogListReq;
import com.avic.system.controller.request.GetSystemUserListReq;
import com.avic.system.controller.request.LoginReq;
import com.avic.system.controller.request.ModifyMeReq;
import com.avic.system.controller.request.ModifySystemUserReq;
import com.avic.system.controller.request.ModifySystemUserStateReq;
import com.avic.system.controller.result.CreateSystemUserRes;
import com.avic.system.controller.result.GetLoginLogListRes;
import com.avic.system.controller.result.GetMeInfo;
import com.avic.system.controller.result.GetSystemUserListRes;
import com.avic.system.controller.result.GetUserAndRoleRes;
import com.avic.system.controller.result.GetUserRightRes;
import com.avic.system.controller.result.LoginRes;
import com.avic.system.controller.result.ResetUserPasswordRes;
import com.avic.system.dal.condition.FindLoginLogListCondition;
import com.avic.system.dal.condition.PageQueryUserCondition;
import com.avic.system.dal.model.LoginLog;
import com.avic.system.dal.model.SystemPermission;
import com.avic.system.dal.model.SystemUser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;


@Slf4j
@RestController
@RequestMapping("/system/user")
@Api(tags = "系统用户", description = "用户登入&创建用户&修改信息&禁启用&获取用户详情接口")
public class SystemUserController extends AbstractFacadeImpl {

    @ApiOperation(value = "用户登入", notes = "登入成功后，response里面的信息会在gateway里面替换成token")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "loginReq", required = true, dataType = "LoginReq"),
            @ApiImplicitParam(name = "real-ip", paramType = "header", value = "由网关转换放入请求头中，可以不用填写")
    })
    @ApiResponses({
            @ApiResponse(code = 100002, message = "登录账号错误"),
            @ApiResponse(code = 100004, message = "密码错误"),
            @ApiResponse(code = 100005, message = "当前账号被禁用")
    })
    @PostMapping("login")
    public LoginRes login(@RequestBody LoginReq loginReq,
                          @RequestHeader(value = UserConstant.HEADER_X_REAL_IP, required = false) String requestIp) {
        final LoginRes result = new LoginRes();
        return serviceExecuteTemplate.executeService(result, new ServiceCallBack() {
            @Override
            public void check() throws Exception {
                AssertUtil.isNotBlank(loginReq.getUserLoginName(), "userLoginName is blank");
                AssertUtil.isNotBlank(loginReq.getPassword(), "password is blank");
                log.info("用户登入：userLoginName = {}", loginReq.getUserLoginName());
            }

            @Override
            public void doService() throws Exception {
                SystemUser systemUser = systemUserService.queryUserForLogin(loginReq.getUserLoginName(), loginReq.getPassword(), requestIp);
                // 设置会员信息到result
                result.setUserId(systemUser.getId());

                UserRightInfo userRightInfo = new UserRightInfo();
                userRightInfo.setUserName(systemUser.getUserName());
                // 获取用户菜单数据
                List<UserMenuInfo> userMenus = SystemMenuConvertor.userSystemMenusConUserMenuInfo(
                        systemUserService.getUserMenuData(loginReq.getUserLoginName(), systemUser.getId()));
                userRightInfo.setMenus(userMenus);

                // 获取权限数据
                if (StringUtils.equals(UserTypeEnums.ADMIN.getUserType(), loginReq.getUserLoginName())) {
                    log.info("当前用户为admin，不查询权限数据");
                    userRightInfo.setUserType(UserTypeEnums.ADMIN.getUserType());
                } else {
                    log.info("当前用户不是admin，查询权限数据");
                    userRightInfo.setUserType(UserTypeEnums.COMMON.getUserType());
                    List<SystemPermission> systemPermissions = systemUserService.getUserPermission(systemUser.getId());
                    if (null != systemPermissions && systemPermissions.size() > 0) {
                        List<String> permissionCodes = new ArrayList<>();
                        systemPermissions.forEach(systemPermission -> {
                            permissionCodes.add(systemPermission.getPermissionCode());
                        });
                        userRightInfo.setPermissionCodes(permissionCodes);
                    }
                }
                // 数据存缓存
                redisTemplate.opsForValue().set(CacheConstant.USER_INFO + result.getUserId(), userRightInfo, 1, TimeUnit.DAYS);
                result.setSuccess(true);
            }
        });
    }


    @ApiOperation(value = "获取用户菜单和权限数据", notes = "获取用户菜单和权限数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "current-user-id", paramType = "header", value = "由网关Token转换放入请求头中,可以不用填写")
    })
    @GetMapping("right")
    public GetUserRightRes userRight(@RequestHeader(value = UserConstant.HEADER_CURRENT_USER_ID_KEY, required = false) String currentUserId) {
        log.info("获取用户菜单和权限数据--pageGetSystemUser");
        final GetUserRightRes result = new GetUserRightRes();
        return serviceExecuteTemplate.executeService(result, new ServiceCallBack() {
            @Override
            public void check() throws Exception {
                AssertUtil.isNotBlank(currentUserId, "user id is blank");
            }

            @Override
            public void doService() throws Exception {

                UserRightInfo reidsUserRightInfo = (UserRightInfo) redisTemplate.opsForValue().get(CacheConstant.USER_INFO + currentUserId);
                if (null != reidsUserRightInfo) {
                    log.info("从缓存中获取到用户 {} 的权限数据", currentUserId);
                    result.setMenus(reidsUserRightInfo.getMenus());
                    result.setPermissionCodes(reidsUserRightInfo.getPermissionCodes());
                    result.setUserType(reidsUserRightInfo.getUserType());
                    result.setUserName(reidsUserRightInfo.getUserName());
                } else {
                    UserRightInfo userRightInfo = new UserRightInfo();
                    log.info("从DB中获取到用户 {} 的权限数据", currentUserId);
                    SystemUser systemUser = systemUserService.getUserByUserId(currentUserId);
                    userRightInfo.setUserName(systemUser.getUserName());
                    result.setUserName(systemUser.getUserName());
                    // 获取用户菜单数据
                    List<UserMenuInfo> userMenus = SystemMenuConvertor.userSystemMenusConUserMenuInfo(
                            systemUserService.getUserMenuData(systemUser.getUserLoginName(), systemUser.getId()));
                    result.setMenus(userMenus);
                    userRightInfo.setMenus(userMenus);
                    // 获取权限数据
                    if (StringUtils.equals(UserTypeEnums.ADMIN.getUserType(), systemUser.getUserLoginName())) {
                        log.info("当前用户为admin，不查询权限数据");
                        result.setUserType(UserTypeEnums.ADMIN.getUserType());
                        userRightInfo.setUserType(UserTypeEnums.ADMIN.getUserType());
                    } else {
                        log.info("当前用户不是admin，查询权限数据");
                        result.setUserType(UserTypeEnums.COMMON.getUserType());
                        List<SystemPermission> systemPermissions = systemUserService.getUserPermission(systemUser.getId());
                        if (null != systemPermissions && systemPermissions.size() > 0) {
                            List<String> permissionCodes = new ArrayList<>();
                            systemPermissions.forEach(systemPermission -> {
                                permissionCodes.add(systemPermission.getPermissionCode());
                            });
                            result.setPermissionCodes(permissionCodes);
                            userRightInfo.setPermissionCodes(permissionCodes);
                        }
                    }
                    // 数据存缓存
                    log.info("更新用户 {} 的缓存数据", currentUserId);
                    redisTemplate.opsForValue().set(CacheConstant.USER_INFO + currentUserId, userRightInfo, 1, TimeUnit.DAYS);
                }
                result.setSuccess(true);
            }
        });
    }

    @ApiOperation(value = "退出登入", notes = "退出登入")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "current-user-id", paramType = "header", value = "由网关Token转换放入请求头中", required = false)
    })
    @PostMapping("logout")
    public BaseResponse logout(@RequestHeader(value = UserConstant.HEADER_CURRENT_USER_ID_KEY) String currentUserId) {
        log.info("退出登入--logout");
        final BaseResponse result = new BaseResponse();
        return serviceExecuteTemplate.executeService(result, new ServiceCallBack() {
            @Override
            public void check() throws Exception {
                AssertUtil.isNotBlank(currentUserId, "user id is blank");
            }

            @Override
            public void doService() throws Exception {
                if (LocalCacheConstant.LOGIN_USER_ID.containsKey(currentUserId)) {
                    log.info("退出登入，删除用户 {} 的权限缓存数据", currentUserId);
                    redisTemplate.delete(CacheConstant.USER_INFO + currentUserId);

                    loginLogService.updateLoginDuration(currentUserId);
                }
                result.setSuccess(true);
            }
        });
    }

    @ApiOperation(value = "分页获取系统用户数据", notes = "管理平台里面的用户列表数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "getSystemUserListReq", required = true, dataType = "GetSystemUserListReq")
    })
    @PostMapping("list")
    public GetSystemUserListRes pageGetSystemUser(@RequestBody GetSystemUserListReq getSystemUserListReq) {
        log.info("分页获取系统用户数据--pageGetSystemUser");
        final GetSystemUserListRes result = new GetSystemUserListRes();
        return serviceExecuteTemplate.executeService(result, new ServiceCallBack() {
            @Override
            public void check() throws Exception {

                AssertUtil.isTrue(getSystemUserListReq.getCurrentPage() > 0,
                        BizErrorCode.PARAM_ERROR, "pageSize必须大于0");
            }

            @Override
            public void doService() throws Exception {
                PageQueryUserCondition pageQueryUserCondition =
                        new PageQueryUserCondition(getSystemUserListReq.getCurrentPage(), getSystemUserListReq.getPageSize());
                pageQueryUserCondition.setUserLoginName(getSystemUserListReq.getUserLoginName());
                pageQueryUserCondition.setUserName(getSystemUserListReq.getUserName());

                // 查询数据
                List<SystemUser> systemUsers = systemUserService.querySystemUserList(pageQueryUserCondition);
                if (null != systemUsers && systemUsers.size() > 0) {
                    // 转换成info对象
                    List<SystemUserListInfo> systemUserListInfoList = new ArrayList<>();
                    systemUsers.forEach(pageSystemUser -> {
                        systemUserListInfoList.add(SystemUserConvertor.systemUserConInfo(pageSystemUser));
                    });
                    result.setUserList(systemUserListInfoList);
                }
                result.setTotalRecord(systemUserService.queryTotalRecords(pageQueryUserCondition));
                result.setSuccess(true);
            }
        });
    }

    @ApiOperation(value = "创建用户")
    @ApiResponses({
            @ApiResponse(code = 100006, message = "用户登录名称已经存在")
    })
    @PostMapping
    public CreateSystemUserRes createSystemUser(@RequestBody CreateSystemUserReq createSystemUserReq,
                                                @RequestHeader(value = UserConstant.HEADER_CURRENT_USER_ID_KEY, required = false) String currentUserId) {
        log.info("创建用户--createSystemUser");
        final CreateSystemUserRes result = new CreateSystemUserRes();
        return serviceExecuteTemplate.executeService(result, new ServiceCallBack() {
            @Override
            public void check() throws Exception {

                AssertUtil.isNotBlank(createSystemUserReq.getUserLoginName(), "userLoginName is blank");
                AssertUtil.isNotBlank(createSystemUserReq.getPassword(), "password is blank");
                log.info("创建用户：userLoginName = {}", createSystemUserReq.getUserLoginName());
                AssertUtil.isNotBlank(currentUserId, "操作人不能为空");

                AssertUtil.isTrue(StringUtils.equals(currentUserId, "1"), BizErrorCode.PARAM_ERROR, "您不是系统管理员，不能创建用户");
            }

            @Override
            public void doService() throws Exception {
                SystemUser systemUser = new SystemUser();
                systemUser.setUserLoginName(createSystemUserReq.getUserLoginName());
                systemUser.setUserName(createSystemUserReq.getUserName());
                systemUser.setUserDept(createSystemUserReq.getUserDept());
                systemUser.setUserPost(createSystemUserReq.getUserPost());
                systemUser.setPassword(createSystemUserReq.getPassword());
                //设置创建人
                String userId = systemUserService.createUser(systemUser);
                log.info("成功创建用户，ID = {}", userId);
                if (null != createSystemUserReq.getRoleIds() && createSystemUserReq.getRoleIds().size() > 0) {
                    systemUserService.batchCreateUserRole(createSystemUserReq.getRoleIds(), userId);
                }
                result.setUserId(userId);

                // 新建系统日志
                systemLogService.createSystemLog(
                        String.format(SystemLogConstant.CREATE_SYSTEM_UPDATE_STRING, createSystemUserReq.getUserName()), currentUserId);
                result.setSuccess(true);
            }

        });
    }

    @ApiOperation(value = "获取用户和用户的角色数据", notes = "用户修改时用户详情信息，用户和角色")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", paramType = "path", value = "用户ID", required = true)
    })
    @ApiResponses({
            @ApiResponse(code = 100006, message = "用户登录名称已经存在")
    })
    @GetMapping("userDetail/{userId}")
    public GetUserAndRoleRes getUserAndRoleRes(@PathVariable("userId") String userId) {
        log.info("获取用户、用户所有用的角色数据--getUserAndRoleRes");
        final GetUserAndRoleRes result = new GetUserAndRoleRes();
        return serviceExecuteTemplate.executeService(result, new ServiceCallBack() {
            @Override
            public void check() throws Exception {

                AssertUtil.isNotBlank(userId, "userId is blank");
            }

            @Override
            public void doService() throws Exception {

                SystemUser systemUser = systemUserService.getUserByUserId(userId);
                result.setUserId(systemUser.getId());
                result.setUserLoginName(systemUser.getUserLoginName());
                result.setUserName(systemUser.getUserName());
                result.setUserDept(systemUser.getUserDept());
                result.setUserPost(systemUser.getUserPost());
                result.setRoleIds(systemUserService.getUserRoleIds(userId));
                result.setSuccess(true);
            }
        });
    }

    @ApiOperation(value = "获取自己信息", notes = "获取自己信息")
    @ApiResponses({
            @ApiResponse(code = 100006, message = "用户登录名称已经存在")
    })
    @GetMapping("userDetail")
    public GetMeInfo getMeInfo(@RequestHeader(value = UserConstant.HEADER_CURRENT_USER_ID_KEY, required = false) String currentUserId) {
        log.info("获取自己信息--getUserAndRoleRes");
        final GetMeInfo result = new GetMeInfo();
        return serviceExecuteTemplate.executeService(result, new ServiceCallBack() {
            @Override
            public void check() throws Exception {

                AssertUtil.isNotBlank(currentUserId, "userId is blank");
            }

            @Override
            public void doService() throws Exception {
                SystemUser systemUser = systemUserService.getUserByUserId(currentUserId);
                result.setUserId(systemUser.getId());
                result.setUserLoginName(systemUser.getUserLoginName());
                result.setUserName(systemUser.getUserName());
                result.setUserDept(systemUser.getUserDept());
                result.setUserPost(systemUser.getUserPost());
                result.setSuccess(true);
            }
        });
    }

    @ApiOperation(value = "更新用户数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "modifySystemUserReq", required = true, dataType = "ModifySystemUserReq")
    })
    @ApiResponses({
            @ApiResponse(code = 100006, message = "用户登录名称已经存在"),
            @ApiResponse(code = 100007, message = "用户不存在")
    })
    @PutMapping
    public BaseResponse modifySystemUser(@RequestBody ModifySystemUserReq modifySystemUserReq,
                                         @RequestHeader(value = UserConstant.HEADER_CURRENT_USER_ID_KEY, required = false) String currentUserId) {
        final BaseResponse result = new BaseResponse();
        return serviceExecuteTemplate.executeService(result, new ServiceCallBack() {
            @Override
            public void check() throws Exception {

                AssertUtil.isNotBlank(modifySystemUserReq.getUserId(), "userId is blank");
                AssertUtil.isNotBlank(currentUserId, "操作人不能为空");
            }

            @Override
            public void doService() throws Exception {
                SystemUser systemUser = new SystemUser();
                systemUser.setId(modifySystemUserReq.getUserId());
                systemUser.setUserLoginName(modifySystemUserReq.getUserLoginName());
                systemUser.setUserName(modifySystemUserReq.getUserName());
                systemUser.setUserPost(modifySystemUserReq.getUserPost());
                systemUser.setUserDept(modifySystemUserReq.getUserDept());
                systemUser.setModifyId(currentUserId);
                systemUserService.updateUser(modifySystemUserReq.getRoleIds(), systemUser);

                // 新建系统日志
                systemLogService.createSystemLog(
                        String.format(SystemLogConstant.UPDATE_SYSTEM_UPDATE_STRING,
                                modifySystemUserReq.getUserLoginName(), objectMapper.writeValueAsString(modifySystemUserReq)), currentUserId);


                result.setSuccess(true);
            }
        });
    }

    @ApiOperation(value = "更新自己的用户数据")
    @ApiResponses({
            @ApiResponse(code = 100006, message = "用户登录名称已经存在"),
            @ApiResponse(code = 100007, message = "用户不存在")
    })
    @PutMapping("me")
    public BaseResponse modifyMe(@RequestBody ModifyMeReq modifyMeReq,
                                 @RequestHeader(value = UserConstant.HEADER_CURRENT_USER_ID_KEY, required = false) String currentUserId) {
        final BaseResponse result = new BaseResponse();
        return serviceExecuteTemplate.executeService(result, new ServiceCallBack() {
            @Override
            public void check() throws Exception {

                AssertUtil.isNotBlank(currentUserId, "操作人不能为空");
            }

            @Override
            public void doService() throws Exception {
                SystemUser systemUser = new SystemUser();
                systemUser.setId(currentUserId);
                systemUser.setUserLoginName(modifyMeReq.getUserLoginName());
                systemUser.setUserName(modifyMeReq.getUserName());
                systemUser.setUserPost(modifyMeReq.getUserPost());
                systemUser.setUserDept(modifyMeReq.getUserDept());
                systemUser.setModifyId(currentUserId);
                systemUserService.updateUser(systemUser);

                // 新建系统日志
                systemLogService.createSystemLog(
                        String.format(SystemLogConstant.UPDATE_SYSTEM_UPDATE_STRING,
                                modifyMeReq.getUserLoginName(), objectMapper.writeValueAsString(modifyMeReq)), currentUserId);
                result.setSuccess(true);
            }
        });
    }

    @ApiOperation(value = "禁用用户", notes = "账号不可删除，只能禁用")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "modifySystemUserStateReq", required = true, dataType = "ModifySystemUserStateReq")
    })
    @PutMapping("disable")
    public BaseResponse disable(@RequestBody ModifySystemUserStateReq modifySystemUserStateReq,
                                @RequestHeader(value = UserConstant.HEADER_CURRENT_USER_ID_KEY, required = false) String currentUserId) {
        log.info("禁用--disable");
        final BaseResponse result = new BaseResponse();
        return serviceExecuteTemplate.executeService(result, new ServiceCallBack() {
            @Override
            public void check() throws Exception {
                AssertUtil.isNotBlank(modifySystemUserStateReq.getUserId(), "userId is blank");
                AssertUtil.isNotBlank(currentUserId, "操作人不能为空");
            }

            @Override
            public void doService() throws Exception {
                SystemUser systemUser = systemUserService.getUserByUserId(modifySystemUserStateReq.getUserId());
                AssertUtil.isTrue(null != systemUser, BizErrorCode.PARAM_ERROR, "用户账号不存在");
                systemUserService.updateUserState(UserStateEnums.DISABLE.getState(), modifySystemUserStateReq.getUserId());

                // 新建系统日志
                systemLogService.createSystemLog(
                        String.format(SystemLogConstant.DISABLE_SYSTEM_UPDATE_STRING,
                                systemUser.getUserLoginName(), modifySystemUserStateReq.getUserId()), currentUserId);
                result.setSuccess(true);
            }
        });
    }

    @ApiOperation(value = "恢复账号", notes = "账号被禁用后可通过该方法启动")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "modifySystemUserStateReq", required = true, dataType = "ModifySystemUserStateReq")
    })
    @PutMapping("enable")
    public BaseResponse enable(@RequestBody ModifySystemUserStateReq modifySystemUserStateReq,
                               @RequestHeader(value = UserConstant.HEADER_CURRENT_USER_ID_KEY, required = false) String currentUserId) {
        log.info("启用用户--enable");
        final BaseResponse result = new BaseResponse();
        return serviceExecuteTemplate.executeService(result, new ServiceCallBack() {
            @Override
            public void check() throws Exception {
                AssertUtil.isNotBlank(modifySystemUserStateReq.getUserId(), "userId is blank");
                AssertUtil.isNotBlank(currentUserId, "操作人不能为空");
            }

            @Override
            public void doService() throws Exception {
                SystemUser systemUser = systemUserService.getUserByUserId(modifySystemUserStateReq.getUserId());
                AssertUtil.isTrue(null != systemUser, BizErrorCode.PARAM_ERROR, "用户账号不存在");

                systemUserService.updateUserState(UserStateEnums.ENABLE.getState(), modifySystemUserStateReq.getUserId());

                // 新建系统日志
                systemLogService.createSystemLog(
                        String.format(SystemLogConstant.ENABLE_SYSTEM_UPDATE_STRING,
                                systemUser.getUserLoginName(), modifySystemUserStateReq.getUserId()), currentUserId);
                result.setSuccess(true);
            }
        });
    }

    @ApiOperation(value = "登入日志列表管理", notes = "登入日志列表管理")
    @PostMapping("getUserLoginLog")
    public GetLoginLogListRes getLoginLogList(@RequestBody GetLoginLogListReq getLoginLogListReq,
                                              @RequestHeader(value = UserConstant.HEADER_CURRENT_USER_ID_KEY, required = false) String currentUserId) {
        log.info("登入日志列表管理--getLoginLogList");
        final GetLoginLogListRes result = new GetLoginLogListRes();
        return serviceExecuteTemplate.executeService(result, new ServiceCallBack() {
            @Override
            public void check() throws Exception {

                AssertUtil.isTrue(getLoginLogListReq.getCurrentPage() > 0,
                        BizErrorCode.PARAM_ERROR, "查看页数必须大于零");
                log.info("查看用户的登入日志 {}", currentUserId);
            }

            @Override
            public void doService() throws Exception {
                FindLoginLogListCondition findLoginLogListCondition =
                        new FindLoginLogListCondition(getLoginLogListReq.getCurrentPage(), getLoginLogListReq.getPageSize());
                findLoginLogListCondition.setLoginBeginTime(getLoginLogListReq.getLoginBeginTime());
                findLoginLogListCondition.setLoginEndTime(getLoginLogListReq.getLoginEndTime());
                findLoginLogListCondition.setUserLoginName(getLoginLogListReq.getUserLoginName());
                findLoginLogListCondition.setUserId(StringUtils.EMPTY);

                if (!StringUtils.equals(currentUserId, "1")) {
                    findLoginLogListCondition.setUserId(currentUserId);
                }

                List<LoginLog> loginLogs = loginLogService.loginLogList(findLoginLogListCondition);
                result.setDataList(SystemUserConvertor.loginLogListToLoginLogInfoList(loginLogs));
                result.setTotalRecord(loginLogService.loginLogListTotalCount(findLoginLogListCondition));
                result.setSuccess(true);
            }
        });
    }

    @ApiOperation(value = "修改自己的密码", notes = "修改密码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "current-user-id", paramType = "header", value = "由网关Token转换放入请求头中,可不填", required = false),
            @ApiImplicitParam(name = "changePasswordReq", required = true, dataType = "ChangePasswordReq")
    })
    @PutMapping("changePassword")
    public BaseResponse changePassword(@RequestHeader(value = UserConstant.HEADER_CURRENT_USER_ID_KEY, required = false) String currentUserId,
                                       @RequestBody ChangePasswordReq changePasswordReq) {
        log.info("修改密码--changePassword");
        final BaseResponse result = new BaseResponse();
        return serviceExecuteTemplate.executeService(result, new ServiceCallBack() {
            @Override
            public void check() throws Exception {
                AssertUtil.isNotBlank(currentUserId, "用户ID不能为空");
                AssertUtil.isTrue(!StringUtils.equals(changePasswordReq.getOldPassword(), changePasswordReq.getNewPassword()),
                        BizErrorCode.PARAM_ERROR, "新密码不能以前的密码一样");
            }

            @Override
            public void doService() throws Exception {
                systemUserService.changePassword(changePasswordReq.getOldPassword(), changePasswordReq.getNewPassword(), currentUserId);

                // 新建系统日志
                systemLogService.createSystemLog(
                        String.format(SystemLogConstant.CHANGE_USER_PASSWORD), currentUserId);
                result.setSuccess(true);
            }
        });
    }

    @ApiOperation(value = "管理员重置密码", notes = "修改密码")
    @PutMapping("resetPassword")
    public ResetUserPasswordRes resetPassword(@RequestHeader(value = UserConstant.HEADER_CURRENT_USER_ID_KEY, required = false) String currentUserId,
                                              @RequestParam("resetUserId") String resetUserId) {
        log.info("管理员重置密码--resetPassword");
        final ResetUserPasswordRes result = new ResetUserPasswordRes();
        return serviceExecuteTemplate.executeService(result, new ServiceCallBack() {
            @Override
            public void check() throws Exception {
                AssertUtil.isTrue(StringUtils.equals(currentUserId, "1"), BizErrorCode.PARAM_ERROR, "你不是管理员，不能重置密码");
                AssertUtil.isNotBlank(resetUserId, "重置的用户对象不能为空");
            }

            @Override
            public void doService() throws Exception {

                String resetPassword = UUID.randomUUID().toString();

                systemUserService.resetPassword(DigestUtils.md5Hex(resetPassword), resetUserId);
                result.setNewPassword(resetPassword);
                // 新建系统日志
                systemLogService.createSystemLog(
                        String.format(SystemLogConstant.SETTTING_PASSWORD), currentUserId);
                result.setSuccess(true);
            }
        });
    }
}
